<template>
    <view class="container">
        <Header :isHomepage="false"></Header>

        <!-- Loading State -->
        <view v-if="loading" class="loading-container">
            <up-loading-icon mode="spinner" size="60"></up-loading-icon>
            <text class="loading-text">加载中...</text>
        </view>

        <!-- Error State -->
        <view v-else-if="error" class="error-container">
            <up-icon name="error-circle" size="80" color="#ff6b6b"></up-icon>
            <text class="error-text">{{ error }}</text>
            <up-button type="primary" @click="retryLoad" class="retry-btn">重新加载</up-button>
        </view>

        <!-- Main Content -->
        <view v-else class="main-content">
            <!-- Memorial Title -->
            <text class="memorial-page-title">{{ memorialDetail.title || '纪念馆' }}</text>

            <!-- Portrait -->
            <view class="portrait-wrapper">
                <image class="portrait-image" :src="memorialDetail.avatar || '/static/default-avatar.png'"
                    mode="aspectFill" @error="handleImageError"></image>
            </view>

            <!-- Name -->
            <text class="deceased-name">{{ memorialDetail.name || '未知' }}</text>

            <!-- Subtitle -->
            <text class="memorial-subtitle">{{ memorialDetail.name || '未知' }}网上纪念馆</text>

            <!-- Birth and Death Dates -->
            <view v-if="memorialDetail.birth_date || memorialDetail.death_date" class="dates-section">
                <text class="dates-text">
                    {{ formatDate(memorialDetail.birth_date) }} - {{ formatDate(memorialDetail.death_date) }}
                </text>
            </view>

            <!-- Offering Icons and Labels -->
            <!-- <view class="offering-section">
                <view 
                v-for="(offering, index) in offeringItems" 
                :key="index"
                class="offering-item" 
                @click="handleOffering(offering)"
                >
                <up-icon :name="offering.icon" size="60" :color="offering.color"></up-icon>
                <text class="offering-label">{{ offering.label }}</text>
                </view>
            </view> -->
            <!-- Offering Icons and Labels -->
            <view class="offering-section">
                <view class="offering-item" @click="goToSacrifice('献花')">
                    <image class="offering-icon" src="/static/detail_image_fllower.png" mode="aspectFit"></image>
                    <!-- Replace with actual icon -->
                    <text class="offering-label">献花</text>
                </view>
                <view class="offering-item" @click="goToSacrifice('献供')">
                    <image class="offering-icon" src="/static/detail_image_shop.png" mode="aspectFit"></image>
                    <!-- Replace with actual icon -->
                    <text class="offering-label">献供</text>
                </view>
                <view class="offering-item" @click="goToSacrifice('点烛')">
                    <image class="offering-icon" src="/static/detail_image.gif" mode="aspectFit"></image>
                    <!-- Replace with actual icon -->
                    <text class="offering-label">点烛</text>
                </view>
                <view class="offering-item" @click="goToSacrifice('上香')">
                    <image class="offering-icon" src="/static/detail_image.png" mode="aspectFit"></image>
                    <!-- Replace with actual icon -->
                    <text class="offering-label">上香</text>
                </view>
                <!-- <view class="offering-item">
                    <image class="offering-icon" src="/static/wine-icon.png" mode="aspectFit"></image>
                    <text class="offering-label">敬酒</text>
                </view> -->
                <view class="offering-item" @click="goToSacrifice('献歌')">
                    <image class="offering-icon" src="/static/detail_image_audio.png" mode="aspectFit"></image>
                    <!-- Replace with actual icon -->
                    <text class="offering-label">献歌</text>
                </view>
            </view>

            <!-- Counts -->
            <!-- <view class="counts-section">
                <view class="count-item">
                    <text class="count-number">{{ memorialDetail.visit_count || 0 }}</text>
                    <text class="count-label">访问</text>
                </view>
                <view class="count-item">
                    <text class="count-number">{{ memorialDetail.worship_count || 0 }}</text>
                    <text class="count-label">祭拜</text>
                </view>
                <view class="count-item">
                    <text class="count-number">{{ memorialDetail.message_count || 0 }}</text>
                    <text class="count-label">留言</text>
                </view>
            </view> -->

            <!-- Function Buttons Grid -->
            <view class="buttons-grid">
                <view v-for="(button, index) in functionButtons" :key="index" class="grid-button"
                    :class="{ active: button.active }" @click="handleButtonClick(button)">
                    <text class="button-text">{{ button.label }}</text>
                    <view v-if="button.active" class="grid-button-dot"></view>
                </view>
            </view>

            <!-- 星语心愿 Section -->
            <!-- <view v-if="memorialDetail.wish" class="wish-section">
                <up-icon name="star" size="60" color="#ffd700"></up-icon>
                <view class="wish-text-area">
                    <text class="wish-title">星语心愿</text>
                    <text class="wish-content">{{ memorialDetail.wish.content }}</text>
                    <text class="wish-dedication">{{ memorialDetail.wish.author }} 敬献</text>
                </view>
            </view> -->

            <!-- Recent Messages -->
            <!-- <view v-if="recentMessages.length > 0" class="recent-messages">
                <view class="section-title">
                    <up-icon name="chat" size="40" color="#667eea"></up-icon>
                    <text class="title-text">最新留言</text>
                </view>
                <view v-for="message in recentMessages" :key="message.id" class="message-item">
                    <view class="message-header">
                        <text class="message-author">{{ message.author }}</text>
                        <text class="message-time">{{ formatTime(message.create_time) }}</text>
                    </view>
                    <text class="message-content">{{ message.content }}</text>
                </view>
                <up-button type="primary" size="small" @click="goToMemorialMessage" class="view-more-btn">
                    查看更多留言
                </up-button>
            </view> -->
        </view>

        <!-- Footer -->
        <view class="footer">
            <view class="footer-links">
                <text @click="goToHome">今生永恒网</text>
                <text>|</text>
                <text @click="goToCreateMemorial">创建纪念馆</text>
                <text>|</text>
                <text @click="goToNews">天堂资讯</text>
                <text>|</text>
                <text @click="goToHelp">帮助中心</text>
            </view>
            <view class="footer-copyright">
                <text>今生永恒网·网上纪念馆 手机版</text>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import { reactive, ref, computed, onMounted } from 'vue'
import { apiMuDetail } from '@/api/graveyard'
import Header from '@/components/header/index.vue'

// 响应式数据
const detailId = ref('')
const loading = ref(true)
const error = ref('')
const memorialDetail = reactive({
    id: '',
    name: '',
    title: '',
    avatar: '',
    birth_date: '',
    death_date: '',
    visit_count: 0,
    worship_count: 0,
    message_count: 0,
    wish: null
})
const recentMessages = ref([])



// 功能按钮配置
const functionButtons = ref([
    { label: '网上墓园', action: 'graveyard', active: true },
    { label: '祭奠留言', action: 'messages', active: false },
    { label: '生平简介', action: 'biography', active: false },
    { label: '纪念文集', action: 'articles', active: false },
    { label: '纪念相册', action: 'album', active: false },
    { label: '纪念视频', action: 'videos', active: false }
])

// 页面加载
onLoad(async (options) => {
    if (options?.id) {
        detailId.value = options.id
        await loadMemorialDetail()
    } else {
        error.value = '缺少纪念馆ID参数'
        loading.value = false
    }
})

// 页面显示时刷新数据
onShow(() => {
    if (detailId.value) {
        loadMemorialDetail()
    }
})

// 加载纪念馆详情
const loadMemorialDetail = async () => {
    try {
        loading.value = true
        error.value = ''

        const res = await apiMuDetail({ id: detailId.value })

        if (res.code === 1 && res.data) {
            // 更新纪念馆详情
            Object.assign(memorialDetail, res.data)

            // 加载最新留言
            await loadRecentMessages()

            // 更新访问计数
            await updateVisitCount()
        } else {
            throw new Error(res.message || '获取纪念馆信息失败')
        }
    } catch (err) {
        console.error('加载纪念馆详情失败:', err)
        error.value = err.message || '加载失败，请重试'
    } finally {
        loading.value = false
    }
}

// 加载最新留言
const loadRecentMessages = async () => {
    try {
        // 这里需要调用获取留言列表的API
        // const res = await getMessageList({ memorial_id: detailId.value, limit: 3 })
        // if (res.code === 1) {
        //   recentMessages.value = res.data.list || []
        // }

        // 临时数据
        recentMessages.value = [
            {
                id: 1,
                author: '张三',
                content: '愿逝者安息，生者坚强。',
                create_time: '2024-01-01 10:00:00'
            },
            {
                id: 2,
                author: '李四',
                content: '缅怀先人，传承家风。',
                create_time: '2024-01-02 15:30:00'
            }
        ]
    } catch (err) {
        console.error('加载最新留言失败:', err)
    }
}

// 更新访问计数
const updateVisitCount = async () => {
    try {
        // 这里需要调用更新访问计数的API
        // await updateVisitCountApi({ memorial_id: detailId.value })
    } catch (err) {
        console.error('更新访问计数失败:', err)
    }
}

// 重新加载
const retryLoad = () => {
    loadMemorialDetail()
}

// 处理图片加载错误
const handleImageError = () => {
    console.log('头像加载失败，使用默认头像')
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return `${date.getFullYear()}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getDate().toString().padStart(2, '0')}`
}

// 格式化时间
const formatTime = (timeStr) => {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
        return '今天'
    } else if (days === 1) {
        return '昨天'
    } else if (days < 7) {
        return `${days}天前`
    } else {
        return formatDate(timeStr)
    }
}

// 处理祭奠操作
const handleOffering = (offering) => {
    uni.navigateTo({
        url: `/pages/sacrifice/index?type=${offering.action}&memorial_id=${detailId.value}`
    })
}

// 处理功能按钮点击
const handleButtonClick = (button) => {
    switch (button.action) {
        case 'graveyard':
            goToMudiDetail()
            break
        case 'messages':
            goToMemorialMessage()
            break
        case 'biography':
            goToUserInfo()
            break
        case 'articles':
            goToMudiArticle()
            break
        case 'album':
            goToAlbum()
            break
        case 'videos':
            goToVideos()
            break
        default:
            uni.showToast({ title: '功能开发中', icon: 'none' })
    }
}

// 导航方法
const goToMemorialMessage = () => {
    uni.navigateTo({
        url: `/pages/memorialManage/memorialMessage/index?id=${detailId.value}`
    })
}

const goToUserInfo = () => {
    uni.navigateTo({
        url: `/pages/memorialManage/userInfo/index?id=${detailId.value}`
    })
}

const goToMudiArticle = () => {
    uni.navigateTo({
        url: `/pages/graveyardManage/article/index?id=${detailId.value}`
    })
}

const goToMudiDetail = () => {
    if (memorialDetail.id) {
        uni.navigateTo({
            url: `/pages/detail/index?id=${memorialDetail.id}`
        })
    } else {
        uni.showToast({ title: '纪念馆信息不完整', icon: 'none' })
    }
}

const goToAlbum = () => {
    uni.navigateTo({
        url: `/pages/graveyardManage/album/index?id=${detailId.value}`
    })
}

const goToVideos = () => {
    uni.navigateTo({
        url: `/pages/graveyardManage/video/index?id=${detailId.value}`
    })
}

// Footer 导航
const goToHome = () => {
    uni.switchTab({ url: '/pages/index/index' })
}

const goToCreateMemorial = () => {
    uni.navigateTo({ url: '/pages/createMemorial/index' })
}

const goToNews = () => {
    uni.navigateTo({ url: '/pages/article/index' })
}

const goToHelp = () => {
    uni.showToast({ title: '帮助中心开发中', icon: 'none' })
}

const goToSacrifice = (text) => {
    uni.navigateTo({ url: `/pages/sacrifice/index?mu_id=${detailId.value}&tabIndex=${text}`   })
}
</script>

<style scoped>
/* 容器样式 */
.container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    padding-bottom: 40rpx;
}

/* 加载状态样式 */
.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 60vh;
    padding: 60rpx;
}

.loading-text {
    margin-top: 30rpx;
    font-size: 28rpx;
    color: #666;
}

/* 错误状态样式 */
.error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 60vh;
    padding: 60rpx;
    text-align: center;
}

.error-text {
    margin: 30rpx 0;
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
}

.retry-btn {
    margin-top: 20rpx;
    width: 200rpx;
    height: 80rpx;
    border-radius: 40rpx;
}

/* Custom Header Styles - Adjusted for this page's layout */
.custom-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 88rpx;
    /* Standard header height */
    padding: 0 20rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
}

.header-left {
    width: 60rpx;
    /* Adjust width for 'X' icon */
    text-align: left;
}

.header-icon {
    font-size: 40rpx;
    color: #333;
}

.header-center {
    flex-grow: 1;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: hidden;
}

.header-title {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.header-subtitle {
    font-size: 20rpx;
    color: #999;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.header-right {
    display: flex;
    align-items: center;
    width: 240rpx;
    /* Adjust width for links and icons */
    justify-content: flex-end;
    /* Align items to the right */
}

.header-link {
    font-size: 26rpx;
    color: #ff9800;
    /* Orange color */
    margin-right: 15rpx;
}

.header-icon-wrapper {
    position: relative;
    /* Needed for red dot positioning */
    margin-left: 15rpx;
    /* Space before user icon */
    margin-right: 15rpx;
    /* Space before menu icon */
}

.user-icon {
    font-size: 40rpx;
    /* Adjust user icon size */
    color: #ff9800;
    /* Orange user icon */
}

.menu-icon {
    font-size: 40rpx;
    /* Adjust menu icon size */
}

.red-dot {
    position: absolute;
    top: 0;
    /* Adjust position */
    right: 0;
    /* Adjust position */
    width: 15rpx;
    /* Size of the dot */
    height: 15rpx;
    background-color: red;
    border-radius: 50%;
}


/* Sub-Banner Styles - Mimic the part below the header */
.sub-banner {
    width: 100%;
    height: 150rpx;
    /* Approximate height from image */
    position: relative;
    overflow: hidden;
}

.sub-banner-bg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    /* The image appears to have a light gradient or subtle pattern */
    /* Use a background image here that matches */
    background-color: #f0f0e0;
    /* Placeholder color/gradient if no image */
}

.sub-banner-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    /* Space between left placeholder and right text */
    align-items: center;
    /* Center vertically */
    padding: 0 40rpx;
    /* Adjust padding */
}

.sub-banner-left {
    width: 150rpx;
    /* Placeholder width for the visible left area */
    /* Add background/gradient if needed to match */
}

.sub-banner-right {
    /* Contains the "今生永恒网 网上纪念馆" part */
    display: flex;
    align-items: flex-end;
    color: #333;
    /* Text color on banner */
    /* Add subtle shadow if needed for readability */
}

.banner-title-area {
    display: flex;
    align-items: flex-end;
}

.banner-main-title {
    font-size: 36rpx;
    /* Adjust font size */
    font-weight: bold;
    margin-right: 10rpx;
}

.banner-sub-area {
    display: flex;
    flex-direction: column;
    font-size: 20rpx;
    /* Adjust font size */
}

.banner-url {
    font-size: 18rpx;
    /* Adjust font size */
    color: #666;
}


/* 主内容样式 */
.main-content {
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
}

/* 纪念馆标题 */
.memorial-page-title {
    font-size: 42rpx;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 30rpx;
    text-align: center;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

/* 头像样式 */
.portrait-wrapper {
    width: 220rpx;
    height: 220rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 20rpx;
    box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
    border: 6rpx solid #fff;
    background: #fff;
}

.portrait-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 逝者姓名 */
.deceased-name {
    font-size: 38rpx;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 12rpx;
    text-align: center;
}

/* 纪念馆副标题 */
.memorial-subtitle {
    font-size: 28rpx;
    color: #7f8c8d;
    margin-bottom: 20rpx;
    text-align: center;
}

/* 生卒日期 */
.dates-section {
    margin-bottom: 30rpx;
}

.dates-text {
    font-size: 26rpx;
    color: #95a5a6;
    text-align: center;
    font-style: italic;
}

/* 祭奠区域 */

/* .offering-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30rpx;
  width: 100%;
  margin-bottom: 40rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.offering-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;
  cursor: pointer;
}

.offering-item:hover {
  background: #f8f9fa;
  transform: translateY(-4rpx);
}

.offering-label {
  font-size: 24rpx;
  color: #555;
  margin-top: 12rpx;
  font-weight: 500;
} */
/* Offering Section */
.offering-section {
    display: flex;
    justify-content: space-around;
    /* Distribute items evenly */
    width: 100%;
    /* Take full width */
    margin-bottom: 40rpx;
    padding: 0 20rpx;
    /* Add some side padding if needed */
}

.offering-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.offering-icon {
    width: 60rpx;
    /* Size of icon image */
    height: 60rpx;
    margin-bottom: 10rpx;
}

.offering-label {
    font-size: 24rpx;
    color: #555;
}

/* 统计区域 */
.counts-section {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-bottom: 40rpx;
    padding: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.count-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
}

.count-number {
    font-size: 32rpx;
    font-weight: 700;
    color: #3498db;
    margin-bottom: 8rpx;
}

.count-label {
    font-size: 24rpx;
    color: #7f8c8d;
    font-weight: 500;
}

/* 功能按钮网格 */
.buttons-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    width: 100%;
    padding: 0 20rpx;
    margin-bottom: 40rpx;
}

.grid-button {
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    position: relative;
    transition: all 0.3s ease;
    cursor: pointer;
}

.grid-button:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 6rpx 25rpx rgba(0, 0, 0, 0.12);
}

.grid-button.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.grid-button.active .button-text {
    color: #fff;
    font-weight: 600;
}

.button-text {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.grid-button-dot {
    position: absolute;
    top: 12rpx;
    right: 12rpx;
    width: 16rpx;
    height: 16rpx;
    background: #ff4757;
    border-radius: 50%;
    box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.3);
}


/* 星语心愿区域 */
.wish-section {
    display: flex;
    align-items: flex-start;
    width: 100%;
    margin-bottom: 40rpx;
    padding: 30rpx;
    background: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
    border-radius: 20rpx;
    box-shadow: 0 6rpx 25rpx rgba(255, 234, 167, 0.3);
}

.wish-text-area {
    flex: 1;
    margin-left: 20rpx;
}

.wish-title {
    font-size: 30rpx;
    font-weight: 700;
    color: #2d3436;
    margin-bottom: 12rpx;
}

.wish-content {
    font-size: 26rpx;
    color: #636e72;
    line-height: 1.6;
    margin-bottom: 12rpx;
}

.wish-dedication {
    font-size: 24rpx;
    color: #74b9ff;
    font-style: italic;
}

/* 最新留言区域 */
.recent-messages {
    width: 100%;
    margin-bottom: 40rpx;
    padding: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.section-title {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
}

.title-text {
    font-size: 30rpx;
    font-weight: 600;
    color: #2c3e50;
    margin-left: 12rpx;
}

.message-item {
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f2f5;
}

.message-item:last-child {
    border-bottom: none;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
}

.message-author {
    font-size: 28rpx;
    font-weight: 600;
    color: #2c3e50;
}

.message-time {
    font-size: 24rpx;
    color: #95a5a6;
    background: #f8f9fa;
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
}

.message-content {
    font-size: 26rpx;
    color: #636e72;
    line-height: 1.6;
}

.view-more-btn {
    margin-top: 24rpx;
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
}


/* 页脚样式 */
.footer {
    margin-top: auto;
    padding: 40rpx 20rpx;
    background: linear-gradient(135deg, #ddd6fe 0%, #e0e7ff 100%);
    text-align: center;
}

.footer-links {
    font-size: 26rpx;
    color: #6366f1;
    margin-bottom: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
}

.footer-links text {
    margin: 0 12rpx;
    cursor: pointer;
    transition: color 0.3s ease;
}

.footer-links text:hover {
    color: #4f46e5;
}

.footer-copyright {
    font-size: 22rpx;
    color: #9ca3af;
}
</style>